﻿using AutoMapper;
using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Read.Api.Application.Commands.OrdersCommands;
using B.S.Orders.Read.Api.DTO;
using MediatR;
using SqlSugar;

namespace B.S.Orders.Read.Api.Application.CommandsHander.OrdersCommandsHander
{
    public class QueryOrdersCommandHander : IRequestHandler<QueryOrdersCommand, APIPaging<List<OrdersDtos>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IConfiguration config;
        private readonly IMapper mapper;

        public QueryOrdersCommandHander(ISqlSugarClient db, IConfiguration config, IMapper mapper)
        {
            this.db = db;
            this.config = config;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<List<OrdersDtos>>> Handle(QueryOrdersCommand request, CancellationToken cancellationToken)
        {

            APIPaging<List<OrdersDtos>> result = new APIPaging<List<OrdersDtos>>();

            var item = db.Queryable<OrdersModel>()
                       .InnerJoin<Documents>((a, b) => a.DocumentsId == b.DocumentsId)
                       .Where((a, b) => a.Del == false)
                       .Select((a, b) => new OrdersDtos
                       {
                           OrdersId = a.OrdersId,
                           ProductName = a.ProductName,
                           ProductNumber = a.ProductNumber,
                           Specifications = a.Specifications,
                           Unit = a.Unit,
                           OrderQuantity = a.OrderQuantity,
                           TypeProduction = a.TypeProduction,
                           StartDate = a.StartDate,
                           CompletionDate = a.CompletionDate,
                           DeliveryDate = a.DeliveryDate,
                           DocumentsId = b.DocumentsId,
                           Del = a.Del,
                           DocumentsName = b.DocumentsName,
                           DocumentsNum = b.DocumentsNum,
                           ProjectId = b.ProjectId,
                           //projectName = b.ProjectId,
                           personnel = b.personnel,
                           Time = b.Time,
                           Remark = b.Remark,
                       });

            result.TotalCount = item.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            item = item.OrderByDescending(a => a.OrdersId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            result.Code = APIEnum.success;
            result.Msg = "查询成功";
            result.Data = mapper.Map<List<OrdersDtos>>(item.ToList());

            return Task.FromResult(result);
        }
    }
}
